package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> seckill_SCRIPT;
    static {
        seckill_SCRIPT=new DefaultRedisScript<>();
        seckill_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        seckill_SCRIPT.setResultType(Long.class);
    }
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService seckillOrderexecutor = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        seckillOrderexecutor.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while (true){
                //获取队列中的订单信息
                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    handleVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.error("订单异常",e);
                }
                //创建订单
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //SimpleRedisLock lock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("redisson:lock:order" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            log.error("不允许重复下单");
            //获取锁失败,返回错误或重试
        }
        try {
            //加锁解决一人一单问题
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }
    private IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long id = UserHolder.getUser().getId();
        //执行lua脚本，判断是否为0
        Long result = stringRedisTemplate.execute(seckill_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), id.toString()
        );
        int r = result.intValue();
        if (r != 0){
            //不为0没有购买资格
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }
        //TODO 有购买资格，下单信息保存到阻塞队列
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        Long userId = UserHolder.getUser().getId();
        voucherOrder.setUserId(userId);

        //创建并放入阻塞队列
        orderTasks.add(voucherOrder);
        //获取代理对象（事务）TODO 面试可能问
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        //返回订单id
        //
        return Result.ok(orderId);
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //查询优惠卷
        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);
        //判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }

        //判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }

        //判断库存
        if (seckillVoucher.getStock()<1){
            return Result.fail("库存不足");
        }

        Long userId = UserHolder.getUser().getId();
        //SimpleRedisLock lock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("redisson:lock:order" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            //获取锁失败,返回错误或重试
            return Result.fail("不允许重复下单");
        }
        try {
            //获取代理对象（事务）TODO 面试可能问
            IVoucherOrderService o = (IVoucherOrderService) AopContext.currentProxy();
            //加锁解决一人一单问题
            return o.getUserExist(voucherId);
        } finally {
            lock.unlock();
        }

        //单体项目下解决一人一单问题
        *//*synchronized (userId.toString().intern()) {
            //获取代理对象（事务）TODO 面试可能问
            IVoucherOrderService o = (IVoucherOrderService) AopContext.currentProxy();
            //加锁解决一人一单问题
            return o.getUserExist(voucherId);
        }*//*
    }*/

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单
        Long userid = voucherOrder.getVoucherId();

            Integer count = query().eq("user_id", userid).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count > 0) {
                //用户已经购买过不允许下单
                log.error("不允许重复下单");
            }

            //扣减库存
            boolean success = iSeckillVoucherService.update()
                    .setSql("stock = stock-1")//TODO 使用乐观锁解决超卖问题
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0)
                    .update();

            if (!success) {
                log.error("抢购失败，库存不足");
            }

            //创建订单
            save(voucherOrder);
        }
    
}
